package com.hongxun.budget.ui.activity.sg;

import android.app.DatePickerDialog;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.dialog.ListDialog;
import com.hongxun.budget.ui.fragment.sg.EditHideProInfoList;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.DateUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.StringUtils;
import com.hongxun.entity.LoginInfo;
import com.hongxun.entity.sg.CYbgcInfo;
import com.hongxun.greenentity.sg.CMiddleCheckEntity;
import com.hongxun.greenentity.sg.CScheduleReportEntity;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.greenentity.tk.DPictureEntity;
import com.hongxun.interfaces.ResponseListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 新增or编辑隐蔽工程记录
 */
public class MiddleCheckAddActivity extends BaseActivity {
    @BindView(R.id.center_title)
    TextView tvTitle;
    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.tv1)
    TextView textView1;
    @BindView(R.id.et1)
    EditText editText1;
    @BindView(R.id.et2)
    EditText editText2;
    @BindView(R.id.tv2)
    TextView textView2;
    @BindView(R.id.btn_add)
    Button btnAdd;
    @BindView(R.id.llayout1)
    LinearLayout layout1;

    private boolean isNewAdd = false;
    private CMiddleCheckEntity entity;
    private EditHideProInfoList infoListFragment;
    private List<BDataDictionaryEntity> dictionaryList = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.sg_activity_middlecheck_add;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        dictionaryList.addAll(DBUtils.getBDataDictionaryEntities("check_type"));
        tvTitle.setText(String.valueOf(SPUtils.get(context, SgStrKey.namexm, "隐蔽工程记录")));
        isNewAdd = getIntent().getBooleanExtra("isNewAdd", false);
        if (isNewAdd) {
            double lat = getIntent().getDoubleExtra("lat", 30.6270786740);
            double lng = getIntent().getDoubleExtra("lng", 104.1520643234);
            String uuidjl = StringUtils.getUuid();
            entity = new CMiddleCheckEntity();
            entity.setGuid(uuidjl);
            entity.setMCMode(getIntent().getStringExtra("tabCode"));
            entity.setPGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, "")));
            entity.setPName(String.valueOf(SPUtils.get(context, SgStrKey.namexm, "")));
            entity.setMCLatitude(lat);
            entity.setMCLongitude(lng);
            entity.setMCDatastate("新增");
            entity.setMCTime(new Date(System.currentTimeMillis()));
            SPUtils.put(context, SgStrKey.uuidjl, uuidjl);
            //默认设置
            textView2.setText(DateUtils.LongToStringyyMMdd_(entity.getMCTime().getTime()));
        } else {
            rightBtn.setVisibility(View.VISIBLE);
            rightBtn.setText("审核");
            rightBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    methodSh();
                }
            });
            entity = SgDBUtils.getCMiddleCheckEntity(String.valueOf(SPUtils.get(context, SgStrKey.uuidjl, "")));
            textView1.setText(entity.getMCType().equals("1") ? "杆塔" : "配电设备");
            editText1.setText(entity.getMCName());
            editText2.setText(entity.getMCHigh());
            textView2.setText(DateUtils.LongToStringyyMMdd_(entity.getMCTime().getTime()));
            setGt(entity.getMCType());
        }
        rightSave.setVisibility(View.VISIBLE);
        rightSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodSblx();
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPUtils.put(context, SgStrKey.uuidxx, "");
                startActivity(new Intent(context, HideProInfoAddActivity.class)
                        .putExtra("isNewAdd", true));
            }
        });
        textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateUtils.showDatePickerDialog(activity, R.layout.sg_dialog_datepicker, listener);
            }
        });
        AddFagment();
    }

    //设备类型选择
    private void methodSblx() {
        new ListDialog<BDataDictionaryEntity>()
                .setDatas(dictionaryList)
                .setTitle("选择记录类别")
                .setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        BDataDictionaryEntity datum = (BDataDictionaryEntity) data[0];
                        textView1.setText(datum.getDValue());
                        entity.setMCType(datum.getDKey());
                        setGt(datum.getDKey());
                    }
                }).show(getFragmentManager(), "");
    }

    //审核
    private void methodSh() {
        List<String> shList = new ArrayList<>();
        shList.add("通过");
        shList.add("不通过");
        new ListDialog<String>()
                .setDatas(shList)
                .setTitle("记录审核")
                .setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        entity.setMCResult(data[0] + "");
                        saveData();
                    }
                }).show(getFragmentManager(), "");
    }

    //隐蔽工程信息记录列表
    private void AddFagment() {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        infoListFragment = new EditHideProInfoList();
        transaction.replace(R.id.flayout1, infoListFragment).commit();
    }

    private void setGt(String mcType) {
        if (mcType.equals("1")) {
            layout1.setVisibility(View.VISIBLE);
        } else {
            layout1.setVisibility(View.GONE);
            entity.setMCHigh("");
        }
    }

    //保存
    private void saveData() {
        String trim1 = textView1.getText().toString().trim();
        if (trim1.isEmpty()) {
            showMsg("请选择类型");
            return;
        }
        String trim2 = editText1.getText().toString().trim();
        if (trim2.isEmpty()) {
            showMsg("请设置编号/名称");
            return;
        }
        String trim3 = editText2.getText().toString().trim();
        entity.setMCType(trim1.equals("杆塔") ? "1" : "2");
        entity.setMCName(trim2);
        entity.setMCHigh(trim3);
        Observable.just(entity).subscribeOn(Schedulers.io()).map(new Func1<CMiddleCheckEntity, Boolean>() {
            @Override
            public Boolean call(CMiddleCheckEntity entity) {
                LoginInfo loginInfo = LoginInfo.getInfo(context);
                entity.setMCUser(loginInfo.getUserId());
                entity.setMCUsername(loginInfo.getUsername());
                SgDBUtils.upDataCMiddleCheckEntity(entity);
                //新增或更新施工进度：中间检查
                String uuidxm = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
                //进度生成或更新最近记录时间
                SgDBUtils.updateCSEntity(context, uuidxm, "中间检查");
                if (!isNewAdd) return false;
                List<CYbgcInfo> list = infoListFragment.getBeanList();
                Map<String, Integer> map = new HashMap<>();
                for (CYbgcInfo info : list) {
                    String detail = info.getName() + "(" + info.getTvr5() + ")";
                    if (map.containsKey(detail)) {
                        int i = map.get(detail) + 1;
                        map.remove(detail);//replace方法无用
                        map.put(detail, i);
                    } else {
                        map.put(detail, 1);
                    }
                }
                String sRDetails = "";
                for (Map.Entry<String, Integer> entry : map.entrySet()) {
                    sRDetails = entry.getKey() + "(" + map.get(entry.getKey()) + ")\n";
                }
                //生成材料到场记录
                CScheduleReportEntity reportEntity = new CScheduleReportEntity();
                reportEntity.setGuid(StringUtils.getUuid());
                reportEntity.setPGuid(uuidxm);
                reportEntity.setSGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidjd, "")));
                reportEntity.setSName("中间检查");
                reportEntity.setSRDatastate("新增");
                reportEntity.setSRAddtime(new Date(System.currentTimeMillis()));
                String res = entity.getMCResult() == null ? "不通过" : "通过";
                String type = entity.getMCType().equals("1") ? "#杆塔" : "#配电设备";
                reportEntity.setSRTheme(entity.getMCName() + type + "(" + res + ")");
                reportEntity.setSRDetails(sRDetails);
                reportEntity.setSRUpdatetime(new Date(System.currentTimeMillis()));//保存一次更新一次时间
                reportEntity.setSRUser(entity.getMCUser());
                reportEntity.setSRUsername(entity.getMCUsername());
                SgDBUtils.upDateCScheduleReportEntity(reportEntity);
                //隐蔽工程照片："检查,tz"->"进度,zl","检查,xc"->"进度,xc"
                for (CYbgcInfo info : list) {
                    List<DPictureEntity> list1 = SgDBUtils.getDPictureEntityList(info.getUuid());
                    for (DPictureEntity pictureEntity : list1) {
                        pictureEntity.setGuid(StringUtils.getUuid());
                        pictureEntity.setPPGuid(reportEntity.getGuid());
                        if (StringUtils.getNull(pictureEntity.getPLabel()).equals("检查,xc")) {
                            pictureEntity.setPLabel("进度,xc");
                        } else {
                            pictureEntity.setPLabel("进度,zl");
                        }
                        SgDBUtils.upDataDPictureEntity(pictureEntity);
                    }
                }
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean b) {
                finish();
            }
        });
    }

    DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String month1 = "";
            String dayOfMonth1 = "";
            if (month < 10) {
                if (month == 9) {
                    month1 = "" + (month + 1);
                } else {
                    month1 = "0" + (month + 1);
                }
            } else {
                month1 = (month + 1) + "";
            }
            if (dayOfMonth < 10) {
                dayOfMonth1 = "0" + dayOfMonth;
            } else {
                dayOfMonth1 = dayOfMonth + "";
            }
            String time = year + "-" + month1 + "-" + dayOfMonth1;
            textView2.setText(time + "");
            entity.setMCTime(new Date(DateUtils.StringTOLongyyMMdd2(time)));
        }
    };
}
